<template>
  <div>
    <!-- 顶部导航栏 -->
    <header class="exchange-header">
      <a href="#" class="exchange-logo">
        <i class="fas fa-chart-line mr-2"></i>
        区块链证券交易所
      </a>
      
      <!-- 用户信息 -->
      <div class="user-info">
        <div class="user-avatar">
          <i class="fas fa-user"></i>
        </div>
        <span class="user-name">{{ user?.username }}</span>
        <span class="user-role">{{ user?.role }}</span>
        <span class="wallet-address ml-3">{{ shortenAddress(user?.eoaAddress) }}</span>
        
        <button class="btn btn-sm btn-outline-light ml-3" @click="handleLogout">
          <i class="fas fa-sign-out-alt"></i>
        </button>
      </div>
    </header>

    <!-- 侧边栏 -->
    <aside class="exchange-sidebar">
      <div class="sidebar-sticky">
        <div class="sidebar-heading">主要导航</div>
        <ul class="sidebar-nav">
          <li class="sidebar-nav-item">
            <router-link to="/" class="sidebar-nav-link" :class="{ active: currentRoute === 'Home' }">
              <i class="fas fa-home"></i>
              <span>首页</span>
            </router-link>
          </li>
          <li class="sidebar-nav-item">
            <router-link to="/user" class="sidebar-nav-link" :class="{ active: currentRoute === 'User' }">
              <i class="fas fa-wallet"></i>
              <span>我的资产</span>
            </router-link>
          </li>
          <li class="sidebar-nav-item">
            <router-link to="/admin" class="sidebar-nav-link" :class="{ active: currentRoute === 'Admin' }">
              <i class="fas fa-chart-bar"></i>
              <span>股票管理</span>
            </router-link>
          </li>
        </ul>
        
        <div class="sidebar-heading mt-4">系统信息</div>
        <div class="px-3 py-2">
          <div class="text-muted">
            <div><small><i class="fas fa-network-wired mr-2"></i>{{ networkInfo }}</small></div>
            <div><small><i class="fas fa-wallet mr-2"></i>{{ walletConnected ? '已连接' : '未连接' }}</small></div>
            <div v-if="contractStore.currentAccount"><small><i class="fas fa-user mr-2"></i>{{ shortenAddress(contractStore.currentAccount) }}</small></div>
          </div>
        </div>
      </div>
    </aside>

    <!-- 主内容区域 -->
    <main class="exchange-content">
      <!-- 系统消息区域 -->
      <div v-if="systemMessage" class="alert" :class="systemMessage.type" style="margin-bottom: 20px;">
        {{ systemMessage.text }}
      </div>
      
      <!-- 页面标题 -->
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0">股票市场概览</h1>
        <button class="btn btn-primary" @click="loadStockList">
          <i class="fas fa-sync-alt mr-1"></i>刷新
        </button>
      </div>
      
      <!-- 内容区域 -->
      <div class="exchange-card">
        <div class="exchange-card-header">
          <h5 class="exchange-card-title">
            <i class="fas fa-chart-line mr-2"></i>股票列表
          </h5>
        </div>
        <div class="exchange-card-body p-0">
          <div v-if="loading" class="text-center py-5">
            <div class="loading-spinner mx-auto"></div>
            <p class="mt-3 text-muted">正在加载股票数据...</p>
          </div>
          
          <div v-else-if="stocks.length === 0" class="text-center py-5">
            <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
            <p class="text-muted">暂无股票数据</p>
          </div>
          
          <table v-else class="table stock-table mb-0">
            <thead>
              <tr>
                <th>股票ID</th>
                <th>股票名称</th>
                <th>描述</th>
                <th>总股本</th>
                <th>股东数量</th>
                <th>创建时间</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="stock in stocks" :key="stock.stockId">
                <td><span class="badge badge-primary">{{ stock.stockId }}</span></td>
                <td><strong>{{ stock.name }}</strong></td>
                <td>{{ stock.description }}</td>
                <td>{{ formatNumber(stock.totalShares) }}</td>
                <td>{{ stock.shareholderList?.length || 0 }}</td>
                <td>{{ formatDate(stock.timestamp) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useContractStore } from '@/stores/contract'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const contractStore = useContractStore()

const user = computed(() => authStore.user)
const isAdmin = computed(() => user.value?.role === 'ADMIN')
const currentRoute = computed(() => route.name)

const stocks = ref([])
const loading = ref(true)
const walletConnected = ref(false)
const networkInfo = computed(() => contractStore.networkName || 'Localhost')
const systemMessage = ref(null)

const shortenAddress = (address) => {
  if (!address) return ''
  return `${address.slice(0, 6)}...${address.slice(-4)}`
}

const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num)
}

const formatDate = (timestamp) => {
  if (!timestamp) return '-'
  return new Date(timestamp * 1000).toLocaleString('zh-CN')
}

const showMessage = (text, type = 'alert-info') => {
  systemMessage.value = { text, type }
  setTimeout(() => {
    systemMessage.value = null
  }, 5000)
}

const loadStockList = async () => {
  loading.value = true
  try {
    const nextId = await contractStore.getNextStockId()
    console.log('总股票数:', nextId)
    const stocksList = []
    
    for (let i = 0; i < nextId; i++) {
      try {
        const stock = await contractStore.getStock(i)
        console.log(`股票 ${i}:`, stock)
        if (stock.timestamp > 0) {
          stocksList.push(stock)
        }
      } catch (error) {
        // 股票可能已被删除
        console.log(`股票 ${i} 不存在或已被删除:`, error.message)
      }
    }
    
    console.log('成功加载股票列表:', stocksList)
    stocks.value = stocksList
  } catch (error) {
    console.error('加载股票列表失败:', error)
    showMessage('加载股票列表失败: ' + error.message, 'alert-danger')
  } finally {
    loading.value = false
  }
}

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

onMounted(async () => {
  // 初始化合约连接
  const connected = await contractStore.initProvider()
  walletConnected.value = connected
  
  if (connected) {
    // 检查账户是否匹配（只提示，不阻止浏览）
    const userEoaAddress = user.value?.eoaAddress
    const metamaskAccount = contractStore.currentAccount
    
    if (userEoaAddress && metamaskAccount) {
      if (userEoaAddress.toLowerCase() !== metamaskAccount.toLowerCase()) {
        showMessage(
          `⚠️ 账户不匹配！当前登录：${shortenAddress(userEoaAddress)}，MetaMask：${shortenAddress(metamaskAccount)}。某些操作可能受限。`, 
          'alert-warning'
        )
      } else {
        showMessage('MetaMask 连接成功，账户匹配', 'alert-success')
      }
    } else {
      showMessage('MetaMask 连接成功', 'alert-success')
    }
    
    await loadStockList()
  } else {
    showMessage('请连接 MetaMask 钱包', 'alert-warning')
    loading.value = false
  }
})
</script>

